package com.lovo.sheyingback.controller;

import com.auth0.jwt.JWT;
import com.lovo.sheyingback.bean.SystemDict;
import com.lovo.sheyingback.bean.User;
import com.lovo.sheyingback.bean.form.UserForm;
import com.lovo.sheyingback.result.GlobalHandleException;
import com.lovo.sheyingback.result.ResponseResult;
import com.lovo.sheyingback.result.ResultCode;
import com.lovo.sheyingback.result.UserValid;
import com.lovo.sheyingback.service.UserService;
import com.lovo.sheyingback.util.JWTUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.apache.commons.codec.cli.Digest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Map;

@RestController
@RequestMapping("/users")
@ResponseResult
@Tag(name = "用户控制器UserController")
@SecurityRequirement(name = "bearer-key")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;
    private static final String INIT_PWD = "123456";

    @GetMapping
    @UserValid
    @Operation(summary = "显示所有用户")
    public Object listUser(UserForm userForm) {
        return userService.listUser(userForm.getCurrent(), userForm.getPageSize());
    }

    @GetMapping("/roles/{id}")
    @Operation(summary = "查询已分配和所有角色")
    public Object listUserRole(@PathVariable Integer id) {
        return userService.listUserRole(id);
    }

    @GetMapping("/functions/{id}")
    @Operation(summary = "查询已分配和所有权限")
    public Object listUserFunction(@PathVariable Integer id) {
        return userService.listUserFunction(id);
    }

    @PostMapping("/login")
    @Operation(summary = "登录")
    public Object login(@RequestBody @Valid UserForm userForm) throws GlobalHandleException {
        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        user.setPwd(DigestUtils.sha256Hex(user.getPwd()));
        User loginUser = userService.login(user);
        if (loginUser == null) {
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }
//        // 登录成功，设置session
//        HttpSession session = request.getSession();
//        session.setAttribute("user",loginUser);
        // 登录成功，生成token
        String [] accessTokens = JWTUtil.createToken(user.getUsername(),
                user.getPwd(), Calendar.MINUTE, 30).split(",");
        String [] refreshTokens = JWTUtil.createToken(user.getUsername(),
                user.getPwd(),Calendar.DATE,7).split(",");

        return Map.of("access_token",accessTokens[0],
                "expire_time",accessTokens[1],
                "refresh_token",refreshTokens[0]);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查找用户")
    public Object getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @PostMapping
    @Operation(summary = "增加用户")
    public Object save(@RequestBody @Valid UserForm userForm) {
        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        user.setPwd(DigestUtils.sha256Hex(INIT_PWD));
        user.setType(new SystemDict(userForm.getTypeId()));
        user.setCreateDate(LocalDateTime.now());
        user.setUpdateDate(LocalDateTime.now());
        return userService.insert(user);

    }

    @PutMapping("/assignRole/{id}")
    @Operation(summary = "给用户分配角色")
    public Object assignUserRole(@PathVariable Integer id, @RequestBody UserForm userForm) {
        return userService.assignUserRole(id, userForm.getRoleIds());
    }

    @PutMapping("/assignFunction/{id}")
    @Operation(summary = "给用户分配权限")
    public Object assignUserFunction(@PathVariable Integer id, @RequestBody UserForm userForm) {
        return userService.assignUserFunction(id, userForm.getFunctionIds());
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新用户状态")
    public Object updateStatus(@PathVariable Integer id, Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(new SystemDict(status));
        return userService.update(user);

    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    public Object delete(@PathVariable Integer id) {
        return userService.delete(id);
    }

    @GetMapping("/session")
    @UserValid
    @Operation(summary = "从session中获取用户信息")
    public Object getUserInSession() {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        return user;
    }

    @GetMapping("/token")
    @UserValid
    @Operation(summary = "从token中获取用户信息")
    public Object getUserInToken(){
        return request.getAttribute("user");

    }

    @PostMapping("/refreshToken")
    @Operation(summary = "刷新token")
    public Object refreshToken(String refreshToken) throws GlobalHandleException {
        String username = JWTUtil.getAudience(refreshToken);
        User user = userService.getByUsername(username);
        JWTUtil.verifyToken(refreshToken,user.getPwd());
        String [] accessTokens = JWTUtil.createToken(username,user.getPwd(),Calendar.MINUTE,30).split(",");
        return Map.of("access_token",accessTokens[0],"expire_time",accessTokens[1]);
    }

}
